$(function () {
    layui.use(['element', 'table', 'layer', 'laytpl', 'form'], function () {
        var element = layui.element,
            table = layui.table,
            layer = layui.layer,
            laytpl = layui.laytpl,
            form = layui.form;
        var checkData = [];
        getGatewayData();

        //查
        function getGatewayData() {
            $.ajax({
                type: "post",
                url: ctx + "/gatewayManage/getAll.do",
                data: {},
                dataType: "json",
                success: function (data) {
                    if (data != null) {
                        renderTable(data);
                    }
                }
            });
        }

        function renderTable(data) {
            var tbHeigth = $('.settings-wrap').height();
            table.render({
                elem: '#gatewayTable',
                data: data,
                height: tbHeigth,
                title: '网关信息表',
                toolbar: '#toolbar',
                defaultToolbar: [],
                cols: [[
                    {type: 'radio', fixed: 'left'}
                    , {field: 'ip', title: '网关IP'}
                    , {field: 'gatewayName', title: 'IP简称'}
                    , {field: 'port', title: '端口号'}
                    , {field: 'descrition', title: '备注'}
                    , {field: 'gatewayId', title: '网关Id'}
                ]],
                page: {
                    layout: ['prev', 'page', 'next', 'count', 'skip', 'limit']
                    , groups: 5 //只显示 5 个连续页码
                    , limit: 15  //每页显示条数
                    , limits: [15, 30, 45, 60]
                },
                loading: true,
                done: function () {
                    $('.layui-table-view > .layui-table-box').height(tbHeigth - 41);
                    $('.layui-table-view > .layui-table-box .layui-table-body').height(tbHeigth - 80);
                }
            });
        }

        //头工具栏事件
        table.on('toolbar(gatewayTable)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id); //获取选中行状态
            switch (obj.event) {
                case 'getCheckData':
                    checkData = checkStatus.data;  //获取选中行数据
                    // console.log(checkData);
                    break;
            }
            ;
        });

        // 新增
        $('.addBtn').click(function () {
            var layerIdx = layer.open({
                type: 1,
                title: "新增",
                closeBtn: 1,
                anim: 0,
                area: 'auto',
                content: $('#add-tpl').html()
            });
            form.on('submit(add-param)', function (res) {
                // console.log(res.field); //当前容器的全部表单字段，名值对形式：{name: value}
                addGateway(res.field);
                layer.close(layerIdx);
                return false;
            });
            $(".add-param button[type='cancel']").click(function () {
                layer.close(layerIdx);
                return false;
            });
        });

        // 编辑
        $('.editBtn').click(function () {
            $('.getCheckData').click();
            if (checkData.length === 1) {
                var layerIdx = layer.open({
                    type: 1,
                    title: "编辑",
                    closeBtn: 1,
                    anim: 0,
                    area: 'auto',
                    content: $('#edit-tpl').html(),
                    success: function () {
                        // ip简称赋值
                        $('input#ip').bind('blur', function () {
                            // ip格式验证
                            let pattern = /((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}/g;
                            let val = $(this).val();
                            if(pattern.test(val)){
                                $('input[name="gatewayName"]').val(sliceIp(val))
                            }else{
                                layer.tips('非法的IP地址', '#ip',{
                                    tips: [2, '#F56C6C'],time: 2000
                                });
                            }
                        });
                    }
                });
                form.val("edit-param", checkData[0]);
                form.on('submit(edit-param)', function (res) {
                    // console.log(res.field); //当前容器的全部表单字段，名值对形式：{name: value}
                    updateGateway(res.field);
                    layer.close(layerIdx);
                    return false;
                });
                $(".edit-param button[type='cancel']").click(function () {
                    layer.close(layerIdx);
                    return false;
                });
            } else {
                layer.alert('请选择一条数据')
            }
        });

        // 删除
        $('.delBtn').click(function () {
            $('.getCheckData').click();
            if (checkData.length === 1) {
                var layerIdx = layer.confirm('确认删除?', function (index) {
                    deleteGateway(checkData[0].gatewayId);
                    layer.close(index);
                });
            } else {
                layer.alert('请选择一条数据')
            }
        });


        // 增
        function addGateway(data) {
            $.ajax({
                type: "GET",
                url: ctx + "/gatewayManage/add.do",
                data: data,
                dataType: "json",
                success: function (result) {
                    if (result.code == '000000') {
                        getGatewayData();
                    } else {
                        layer.alert(result.message);
                    }
                }
            });
        }

        //删
        function deleteGateway(gatewayId) {
            $.ajax({
                type: "POST",
                url: ctx + "/gatewayManage/delete.do",
                data: {'gatewayId':gatewayId},
                dataType: "json",
                success: function (result) {
                    if (result.code == '000000') {
                        getGatewayData();
                    } else {
                        layer.alert(result.message);
                    }
                }
            });
        }

        // 改
        function updateGateway(obj) {
            $.ajax({
                url: ctx + "/gatewayManage/update.do",
                type: "POST",
                data: obj,
                success: function (result) {
                    if (result.code == '000000') {
                        getGatewayData();
                    } else {
                        layer.alert(result.message);
                    }
                }
            });
        }

        form.verify({
            ip: function(value, item) {
                let patternIP = /((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}/g;
                if(value == ''){
                    return '必填项不能为空'
                }else if(!patternIP.test(value)){
                    return '非法的IP地址'
                }
            },
            port: function(value, item) {
                let patternPort = /^[1-9]+[0-9]*$/
                if(value == ''){
                    return '必填项不能为空'
                }else if(!patternPort.test(value)){
                    return '端口号需为正整数'
                }
            }
        });

        // ip简称截取
        function sliceIp(ip){
            let arr = ip.split('.');
            if(arr.length == 4){
                return  arr[arr.length - 2] + '.' + arr[arr.length - 1];
            }else{
                return ''
            }
        }

    });
});


